﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Arch.DomainServices.Metadata
{
    internal class MetadataTypeDescriptor : CustomTypeDescriptor
    {
        private readonly IDictionary<string, IList<Attribute>> _attributes;
        private Type _objectType;
        private ICustomTypeDescriptor _parent;

        public MetadataTypeDescriptor(IDictionary<string, IList<Attribute>> attributes,
                                            Type objectType, ICustomTypeDescriptor parent)
            : base(parent)
        {
            _attributes = attributes;
            _objectType = objectType;
            _parent = parent;
        }

        public override PropertyDescriptorCollection GetProperties()
        {
            var baseProperties = base.GetProperties();
            var list = new List<PropertyDescriptor>();

            bool hasCustomAttributes = false;

            foreach (PropertyDescriptor item in baseProperties)
            {
                if (_attributes.ContainsKey(item.Name))
                {
                    var attributes = _attributes[item.Name];
                    if (attributes.Count > 0)
                    {
                        hasCustomAttributes = true;
                        list.Add(new MetadataPropertyDescriptor(item, attributes.ToArray()));
                    }
                    else
                    {
                        list.Add(item);
                    }
                }
                else
                {
                    list.Add(item);
                }
            }

            if (hasCustomAttributes)
            {
                return new PropertyDescriptorCollection(list.ToArray(), true);
            }
            return baseProperties;
        }
    }

}
